import { log } from '@main/core/logger';
import { Result } from '@shared/types.d';
/**
 * 错误响应选项
 */
interface ErrorOptions {
  status?: number;
  code?: number;
  message?: string;
  logError?: boolean;
}

/**
 * 通用响应处理器
 * 统一处理HTTP和IPC的成功/失败响应格式
 */
class HandlerAdapter {
  /**
   * 处理业务函数执行
   *
   * @param businessFunc 业务函数
   * @param args 函数参数
   * @param context 上下文信息（用于日志）
   * @returns 统一格式的响应
   */
  async execute<T>(
    businessFunc: (...args: any[]) => Promise<T>,
    args: any[],
    context: {
      routePath?: string;
      channelName?: string;
      type: 'http' | 'ipc';
    }
  ): Promise<Result<T>> {
    const { routePath, channelName, type } = context;
    const identifier = routePath || channelName || 'unknown';

    try {
      log.debug(`[${type.toUpperCase()}] Executing ${identifier}...`);

      // 打印参数信息
      log.debug(`[${type.toUpperCase()}] Parameters:`, args);

      const result = await businessFunc(...args);

      log.debug(`[${type.toUpperCase()}] ${identifier} executed successfully`);

      return this.success(result);
    } catch (error: any) {
      const errorMessage = error.message || 'Execution failed';

      log.error(`[${type.toUpperCase()}] Error executing ${identifier}:`, error);

      return this.error(errorMessage, {
        status: error.status,
        code: error.code
      });
    }
  }

  /**
   * 创建成功响应
   * @param data 响应数据
   * @param message 可选的成功消息
   * @returns 成功响应
   */
  success<T>(data?: T, message?: string): Result<T> {
    return {
      success: true,
      data,
      message,
      timestamp: Date.now()
    };
  }

  /**
   * 创建错误响应
   * @param error 错误信息
   * @param options 错误选项
   * @returns 错误响应
   */
  error(error: string, options: ErrorOptions = {}): Result {
    const { status = 500, code = status, message = error, logError = false } = options;

    if (logError) {
      log.error('Response error:', error);
    }

    return {
      success: false,
      error: message,
      code,
      timestamp: Date.now()
    };
  }
}

/**
 * 单例实例
 */
const handlerAdapter = new HandlerAdapter();

export default handlerAdapter;
